package com.wanmait.baohan.controller.businessTripController;


import com.github.pagehelper.PageInfo;
import com.wanmait.baohan.pojo.*;
import com.wanmait.baohan.service.TravelApplicationService;
import com.wanmait.baohan.service.TravelApprovalService;
import com.wanmait.baohan.service.TravelLogService;
import com.wanmait.baohan.service.TravelReportServce;
import com.wanmait.baohan.vo.DataVo;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

//出差审批
@Controller
@RequestMapping("/approve")
public class ApproveTravelApplicationController {
    @Resource
    private TravelApprovalService travelApprovalService;
    @Resource
    private TravelApplicationService travelApplicationService;
    @Resource
    private TravelLogService travelLogService;
    @Resource
    private TravelReportServce travelReportServce;


    //高文强   跳转到出差审批页面
    @RequestMapping("approve")
    public void approve ()
    {


    }

    // 高文强 获取所有的出差申请
    @RequestMapping("getMyApplications")
    @ResponseBody
    public  DataVo<TravelApplication>  getMyApplications(Date beginDate, Date endDate, Integer page, Integer limit, String supplierName, Integer node, String planTravelDate, HttpServletRequest request)
    {

        //创建查询条件对象
        TravelApplication travelApplication = new TravelApplication();
        Supplier supplier = new Supplier();
        supplier.setName("".equals(supplierName)?null:supplierName);
        //supplier.setName(supplierName);
        ProcessNode processNode = new ProcessNode();
        processNode.setNode(node);
        travelApplication.setProcessNode(processNode);
        travelApplication.setSupplier(supplier);
        travelApplication.setPlanTravelDate("".equals(planTravelDate)?null:new Date());
        //封装到vo

        DataVo<TravelApplication> dataVo = new DataVo<>();
        PageInfo<TravelApplication> travelApplicationPageInfo = travelApplicationService.selectAll(page, limit, travelApplication, beginDate, endDate);
        List<TravelApplication> list = travelApplicationPageInfo.getList();
        int i =(page - 1) * limit;
        int j =page * limit;
        if(j>list.size()){
            j=(page-1)*limit+(list.size()%limit);
        }
        List<TravelApplication> travelApplications = list.subList(i, j);
        dataVo.setData(travelApplications);

        //getTotal查出的总记录数
        dataVo.setCount((long)list.size());
        return dataVo;
    }

    //跳转到经理出差审批页面
    @RequestMapping("managerApproval")
    public void managerApproval ()
    {

    }

    //跳转到部门出差审批页面
    @RequestMapping("departmentApproval")
    public void departmentApproval ()
    {

    }


    //跳转到运营出差审批页面
    @RequestMapping("operationApproval")
    public void operationApproval ()
    {

    }

    @RequestMapping("getData")
    @ResponseBody
    private DataVo getData(Integer page, Integer limit,String node)
    {
        DataVo dataVo = new DataVo();
        PageInfo<TravelApproval> pageInfo = travelApprovalService.selectAllTravelApproval(page, limit,Integer.parseInt(node));
        List<TravelApproval> list = pageInfo.getList();
        int i =(page - 1) * limit;
        int j =page * limit;
        if(j>list.size()){
            j=(page-1)*limit+(list.size()%limit);
        }
        List<TravelApproval> travelApprovals = list.subList(i, j);
        dataVo.setData(travelApprovals);
        dataVo.setCount((long)list.size());
        return dataVo;
    }

    //跳转到审批详情页面

    @PostMapping("to")
    @ResponseBody
    public void toApporve(String numbering)
    {

    }

    @PostMapping("go")
    @ResponseBody
    public void goApporve(String id)
    {

    }

    @RequestMapping("toApprove")
    public void toApprove(Model model, String numbering)
    {

        int id = Integer.parseInt(numbering);
        TravelApproval travelApproval = travelApprovalService.selectTravelApprovalById(id);
        model.addAttribute("data", travelApproval);


    }



    /**
     * 高文强
     * 查看并添加出差日志页面
     */
    @RequestMapping("travelLog")
    public void travelLog(Model model, String id)
    {

        int ids = Integer.parseInt(id);
        List<TravelLog> travelLogs = travelLogService.selectByTravelApplitionId(ids);
        for (TravelLog travelLog : travelLogs) {
           travelLog.getTravelApplication().setId(ids);

        }
        model.addAttribute("data",travelLogs);
    }

    /**
     * 高文强
     * 查看个人的所有出差记录页面
     */
    @RequestMapping("approveAllLog")
    public void approveAllLog()

    {

    }


    /**
     * 高文强
     * 传输个人的所有出差记录数据
     */
    @RequestMapping("getLog")
    @ResponseBody
    private DataVo getLog(Integer page, Integer limit)
    {
        DataVo dataVo = new DataVo();
        PageInfo<TravelApplication> travelApplicationPageInfo = travelApplicationService.selectMyApplicationCarryOut(page, limit, 1);
        List<TravelApplication> list = travelApplicationPageInfo.getList();
        dataVo.setData(list);
        dataVo.setCount(travelApplicationPageInfo.getTotal());

        return dataVo;
    }


    /**
     * 高文强
     * 保存出差日志并判断是提交还是添加到草稿箱
     */

    @RequestMapping("saveLog")
    @ResponseBody
    private void saveLog(String id,String value,String draftBox)

    {

        TravelLog log = new TravelLog();
        TravelApplication travelApplication = new TravelApplication();
        travelApplication.setId(Integer.parseInt(id));
        log.setTravelApplication(travelApplication);
        Staff staff = new Staff();
        staff.setId(1);
        log.setStaff(staff);
        if(draftBox.equals("1")){
            log.setCommit(true);
        }
        if(draftBox.equals("0")){
            log.setCommit(false);
        }
        log.setContent(value);
        travelLogService.saveTravelLog(log);

    }

    /**
     * 高文强
     * 根据出差申请单id跳转到草稿箱
     */
    @RequestMapping("toDraftBox")
    public void toDraftBox(String id)
    {

    }

    /**
     * 高文强
     * 根据出差申请单id取草稿箱的日志
     */

    @RequestMapping("draftData")
    @ResponseBody
    public DataVo draftData(Integer page, Integer limit, String id)
    {
        DataVo dataVo = new DataVo();
        int ids = Integer.parseInt(id);

        PageInfo<TravelLog> draftBoxBbyId = travelLogService.findDraftBoxBbyId(page, limit, ids);
        List<TravelLog> travelLogs = draftBoxBbyId.getList();
        dataVo.setData(travelLogs);
        dataVo.setCount(draftBoxBbyId.getTotal());
        return dataVo;
    }

    /**
     * 高文强
     * 审批单不通过
     */

    @RequestMapping("saveTheApprovalForm")
    @ResponseBody
    public void saveTheApprovalForm(String id,String node,String value,String state,HttpServletRequest request)
    {
        Staff user = (Staff)request.getSession().getAttribute("user");
        TravelApproval travelApproval = new TravelApproval();
        TravelApplication travelApplication = new TravelApplication();
        ProcessNode processNode = new ProcessNode();
        processNode.setNode(0);
        travelApplication.setId(Integer.parseInt(id));
        travelApplication.setProcessNode(processNode);
        travelApproval.setState(0);
        travelApplication.setState(0);
        travelApproval.setProcessNode(processNode);
        travelApproval.setTravelApplication(travelApplication);
        travelApprovalService.addApprovalInformation(travelApproval);
        travelApplicationService.modifyNode(travelApplication);
        TravelApproval approval = new TravelApproval();
        TravelApplication travelApplication1 = new TravelApplication();
        approval.setStaff(user);
        ProcessNode processNode1 = new ProcessNode();
        travelApplication1.setId(Integer.parseInt(id));
        processNode1.setNode(Integer.parseInt(node));
        approval.setState(0);
        approval.setTravelApplication(travelApplication1);
        approval.setProcessNode(processNode1);
        approval.setApprovalInfo(value);
        travelApprovalService.modifyApprovalStatus(approval);


    }

    /**
     * 高文强
     * 保存审批单通过
     */
    @RequestMapping("approvalForm")
    @ResponseBody
    public void approvalForm(String id,String node,HttpServletRequest request)
    {
        Staff user = (Staff)request.getSession().getAttribute("user");
        TravelApproval travelApproval = new TravelApproval();
        TravelApplication travelApplication = new TravelApplication();
        ProcessNode processNode = new ProcessNode();
        processNode.setNode(Integer.parseInt(node)+1);
        travelApplication.setId(Integer.parseInt(id));
        travelApplication.setProcessNode(processNode);
        if(node.equals("4")){
            travelApproval.setState(2);
            travelApplication.setState(2);
        }
        else{
            travelApproval.setState(1);
            travelApplication.setState(1);
            travelApproval.setProcessNode(processNode);
            travelApproval.setTravelApplication(travelApplication);
            System.out.println(travelApproval.getTravelApplication().getProcessNode().getNode());
            travelApprovalService.addApprovalInformation(travelApproval);
        }
        travelApplicationService.modifyNode(travelApplication);
        TravelApproval approval = new TravelApproval();
        TravelApplication travelApplication1 = new TravelApplication();
        approval.setStaff(user);
        ProcessNode processNode1 = new ProcessNode();
        travelApplication1.setId(Integer.parseInt(id));
        processNode1.setNode(Integer.parseInt(node));
        approval.setState(2);
        approval.setTravelApplication(travelApplication1);
        approval.setProcessNode(processNode1);
        travelApprovalService.modifyApprovalStatus(approval);
    }


    /**
     * 高文强
     * 跳转到出差总结页面
     */
    @RequestMapping("summary")
    public void summary()
    {

    }

    /**
     * 高文强
     * 上传文件并保存到数据库
     */
    @PostMapping("toSummary")
    @ResponseBody
    public DataVo toSummary(Integer id, MultipartFile file,HttpServletRequest request)
    {


        UUID uuid = UUID.randomUUID();
        DataVo dataVo = new DataVo();
        List<String> strings = new ArrayList<>();
        String name = file.getOriginalFilename();
        String[] split = name.split("\\.");
        System.out.println(split.length);
        String filename = uuid+"."+split[1];
        System.out.println(filename);
        String filepath = "D:\\workspace_idea\\baohan\\src\\main\\resources\\static\\sumary/";
        File newfile = new File(filepath+filename);
        //保存到数据库
        TravelReport travelReport = new TravelReport();
        TravelApplication travelApplication = new TravelApplication();
        travelApplication.setId(id);
        Staff user = (Staff) request.getSession().getAttribute("user");
        travelReport.setStaff(user);
        travelReport.setTravelApplication(travelApplication);
        travelReport.setReport(filename);
        travelReportServce.addReport(travelReport);




        try {
            file.transferTo(newfile);
            String str = "上传成功";
            strings.add(str);
            dataVo.setData(strings);
            return  dataVo;

        } catch (IOException e) {
            e.printStackTrace();
            String str = "上传失败";
            strings.add(str);
            dataVo.setData(strings);
            return  dataVo;
        }

    }



    @ResponseBody
    @RequestMapping("download")
    //下载文件
    public void download(HttpServletRequest request, HttpServletResponse response,String filename) throws IOException {

        //获得请求文件名
        System.out.println(filename);

        //设置文件MIME类型
        response.setContentType("application/octet-stream");
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        //读取目标文件，通过response将目标文件写到客户端
        //获取目标文件的绝对路径
        String fullFileName = ResourceUtils.getURL("classpath:").getPath()+ "static/sumary/" +filename;

        System.out.println(fullFileName);

        //System.out.println(fullFileName);
        //读取文件
        InputStream in = new FileInputStream(fullFileName);
        OutputStream out = response.getOutputStream();

        //写文件
        int b;
        while((b=in.read())!= -1)
        {
            out.write(b);
        }

        in.close();
        out.flush();
        out.close();
        System.out.println("@@@@@@@@@@@");


    }

    /**
     * 高文强
     * 预览出差日志
     */

    @RequestMapping("previewFile")
    public  void previewFile(Model model,String names)throws Exception
    {
        final String imagepath = ResourceUtils.getURL("classpath:").getPath()+"static/image/";//解析时候如果doc文件中有图片  图片会保存在此路径
        String filepath = ResourceUtils.getURL("classpath:").getPath()+ "static/sumary/";
        String fileName = names;
        String htmlName = "456.html";
        final String file = filepath + fileName;
        InputStream input = new FileInputStream(new File(file));
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                File file = new File(imagepath + suggestedName);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(content);
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "/image/" + suggestedName;
            }
        });

        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();

       // File htmlFile = new File(filepath + htmlName);
       // OutputStream outStream = new FileOutputStream(htmlFile);

        //也可以使用字符数组流获取解析的内容
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream outStream = new BufferedOutputStream(baos);

        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer serializer = factory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");

        serializer.transform(domSource, streamResult);

        //也可以使用字符数组流获取解析的内容
       String content = baos.toString();
        baos.close();
        outStream.close();
        model.addAttribute("word", content);



    }





}
